//
//  ServiceView.m
//  Jingjing
//
//  Created by user on 15/11/12.
//  Copyright © 2015年 Mikeshihua. All rights reserved.
//

#import "ServiceView.h"
#import "SalonModel.h"
#import "ServiewDeatilViewController.h"
#import "ProductsAndServicesViewController.h"

@interface ServiceView ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,copy)   NSString       * urlString;
@property (nonatomic,strong) UITableView    * serviceTableView;
@property(nonatomic,strong)NSMutableArray* dataArray;
@property (nonatomic, assign)int idx;
@property (nonatomic,assign) int n;
@property(nonatomic,strong) UIView *noDataView;//无网无数据提示
@property(nonatomic,strong)UIView *noNet;


@end

@implementation ServiceView

-(id)initWithFrame:(CGRect)frame andTheDataUrl:(NSString *)urlString
{
    if (self = [super initWithFrame:frame])
    {
        _urlString = urlString;
        self.backgroundColor = [UIColor hexStringToColor:@"#f3f3f3"];
        self.serviceTableView = [[UITableView alloc]initWithFrame:CGRectMake(16.0f, 16.0f, frame.size.width-32.0f, frame.size.height) style:UITableViewStylePlain];
        self.serviceTableView.delegate   = self;
        self.serviceTableView.dataSource = self;
        self.serviceTableView.backgroundColor = [UIColor clearColor];
        [self setExtraCellLineHidden:self.serviceTableView];
        [self addSubview:self.serviceTableView];
        
        self.serviceTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        [self.serviceTableView addSubview:self.noDataView];
        [self.serviceTableView addSubview:self.noNet];
        __weak __typeof(self) weakSelf = self;
        // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
        self.serviceTableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [weakSelf refreshTheProjectTableView];
        }];
        
        
        // 马上进入刷新状态
        [self.serviceTableView.header beginRefreshing];

        
        
        
        

        
    }
    return self;
}
//去掉表格多余分割线
-(void)setExtraCellLineHidden: (UITableView *)tableView
{
    UIView *view = [UIView new];
    view.backgroundColor = [UIColor clearColor];
    [tableView setTableFooterView:view];
}


- (void)getHttpData
{
    
    _noDataView.hidden = TRUE;
    _noNet.hidden = TRUE;
    _n++;
    
    


    
    NSDictionary *dict = @{ @"page.size":[NSNumber numberWithInt:10],@"page.pn":[NSNumber numberWithInt:_idx + 1] };
    [AppGlobalClass PostDataWithNSstring:GETJINGSERVICELIST withDictionary:dict success:^(NSDictionary* dictionary){
        
//        判断是否返回成功
        if([[dictionary objectForKey:@"success"] isEqualToNumber:[NSNumber numberWithBool:TRUE]])
        {
            
            [self.serviceTableView.header endRefreshing];
            [self.serviceTableView.footer setState:MJRefreshStateIdle];
            [self.serviceTableView.footer endRefreshing];
            
            
            if(_idx == 0)
            {
                [self.dataArray removeAllObjects];
            }

            
            NSArray *dataArray = [dictionary objectForKey:@"responseData"];
            NSDictionary* dataDic = [dataArray firstObject];
            
            if([[dataDic objectForKey:@"pages"] intValue] > _idx)
            {
                
               NSArray* rowsArray = [dataDic objectForKey:@"rows"];
               self.dataArray = [[NSMutableArray alloc]initWithCapacity:0];
                for (NSDictionary* rowsDict in rowsArray) {
                    
                    SalonModel *model = [[SalonModel alloc]init];
                    model.serviceName = [rowsDict objectForKey:@"title"];
                    model.serviceNameId = [rowsDict objectForKey:@"jingServiceId"];
                    [self.dataArray addObject:model];
                    
                    
                }

                
                
                _idx++;
            
                [self.serviceTableView reloadData];
                
                if(rowsArray.count < 10)
                {
                    [self.serviceTableView.footer endRefreshingWithNoMoreData];
                }
                else
                {
                    if (_n<2) {
                        self.serviceTableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(AddtoTheProjectTableView)];
                        
                    }
                    
                }
            }
            else
            {
                if (self.dataArray.count==0) {
                    self.noDataView.hidden = FALSE;
                    
                }
                
                [self.serviceTableView.footer endRefreshingWithNoMoreData];
            }
        

            
            
            
            
        }
    
    }failure:^(NSError* error){
        [self.serviceTableView.header endRefreshing];
        [self.serviceTableView.footer setState:MJRefreshStateIdle];
        [self.serviceTableView.footer endRefreshing];
        
        _noDataView.hidden = FALSE;
        [self.dataArray removeAllObjects];
        [self.serviceTableView reloadData];
        
        

        
        
    }networkerror:^(NSString* networkerror){
        
        _noNet.hidden = FALSE;
        [self.dataArray removeAllObjects];
        [self.serviceTableView reloadData];
        [self.serviceTableView .header endRefreshing];
        [self.serviceTableView .footer setState:MJRefreshStateIdle];
        [self.serviceTableView .footer endRefreshing];
       

    }];
    
}


//没网提示
-(UIView *)noNet
{
    if (!_noNet) {
        _noNet = [[UIView alloc]initWithFrame:CGRectMake((_serviceTableView.frame.size.width-200)/2, (_serviceTableView.frame.size.height-200)/2, 200, 235)];
        _noNet.hidden = TRUE;
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(45, 23, 110, 110);
        [button setImage:[UIImage imageNamed:@"img_nonetwork"] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(noResultButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 200 - 44, 200, 44)];
        label.textAlignment = NSTextAlignmentCenter;
        label.numberOfLines = 0;
        NSMutableAttributedString *aString = [[NSMutableAttributedString alloc]initWithString:@"加载失败\n请检查手机是否联网"];
        
        [aString addAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17],
                                 NSForegroundColorAttributeName:[UIColor colorWithWhite:0.098 alpha:1.000],
                                 } range:NSMakeRange(0, 5)];
        
        [aString addAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:12],
                                 NSForegroundColorAttributeName:[UIColor colorWithWhite:0.702 alpha:1.000],
                                 } range:NSMakeRange(5, 9)];
        [label setAttributedText:aString];
        [_noNet addSubview:label];
        [_noNet addSubview:button];
        
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        btn.frame = CGRectMake(60, 210, 80, 25);
        btn.backgroundColor = [UIColor colorWithWhite:0.200 alpha:1.000];
        btn.layer.cornerRadius = 6;
        btn.layer.masksToBounds = YES;
        [btn setTitle:@"重新加载" forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(noResultButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        [_noNet addSubview:btn];
        
    }
    
    return _noNet;
}

-(UIView *)noDataView{
    if (!_noDataView) {
        
        _noDataView = [[UIView alloc]initWithFrame:CGRectMake((_serviceTableView.frame.size.width-200)/2, (_serviceTableView.frame.size.height-200)/2, 200, 200)];
        _noDataView.hidden = TRUE;
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(45, 23, 110, 110);
        [button setImage:[UIImage imageNamed:@"img_nodata"] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(noResultButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 200 - 44, 200, 44)];
        label.text = @"暂无数据\n点击重新加载";
        label.textAlignment = NSTextAlignmentCenter;
        label.numberOfLines = 0;
        label.font = [UIFont systemFontOfSize:14.0f];
        
        label.textColor = [UIColor colorWithWhite:0.000 alpha:0.540];
        [_noDataView addSubview:label];
        [_noDataView addSubview:button];
        
    }
    
    return _noDataView;
}

- (void)buttonAgainTapped:(id)sender
{
    [self.serviceTableView.header beginRefreshing];
}


//刷新表
-(void)refreshTheProjectTableView
{
    
    _idx = 0;
    _n = 0;

    [self getHttpData];
}

//加载更多数据
- (void)AddtoTheProjectTableView
{
    [self getHttpData];
}


#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return self.dataArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
        
        UIView * separtor = [[UIView alloc]initWithFrame:CGRectMake(0.0f, 59.5f, SCREEN_WIDTH - 32.0f, 0.5)];
        separtor.backgroundColor =  [UIColor hexStringToColor:@"#bdbdbd"];
        separtor.tag = 111;
        [cell.contentView addSubview:separtor];//分割线
        
        cell.backgroundColor = [UIColor whiteColor];
        UILabel* nameLabel = [[UILabel alloc]init];
        nameLabel.frame = CGRectMake(24.0f, 10.0f, 200.0f, 40.f);
        nameLabel.textAlignment = NSTextAlignmentLeft;
        nameLabel.font = [UIFont systemFontOfSize:16.0f];
        nameLabel.tag = 100;
        nameLabel.textColor = kColorTEXT;
        [cell addSubview:nameLabel];
        
    }
    
    UIView *separtor = (UIView*)[cell.contentView viewWithTag:111];
    
    if (indexPath.row==_dataArray.count-1) {
        separtor.hidden = YES;
    }else{
        separtor.hidden = NO;
    }

    
    UILabel* nameLabel = [cell viewWithTag:100];
    SalonModel* moedal = [self.dataArray objectAtIndex:indexPath.row];
    nameLabel.text = [NSString stringWithFormat:@"%@",moedal.serviceName];

    
    
    
      return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60;
}


#pragma mark - Table view delegate
// In a xib-based application, navigation from a table can be handled in -tableView:didSelectRowAtIndexPath:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//    获取服务列表每个名字的id
    

    

    if ([_serviceDelegate respondsToSelector:@selector(goToTheServiceDetailViewControllerWith:withID:)])
    {
        SalonModel* moedal = [self.dataArray objectAtIndex:indexPath.row];
        [_serviceDelegate goToTheServiceDetailViewControllerWith:moedal.serviceName withID:moedal.serviceNameId];
    }

    

    
    

}





//cell分割线左对齐
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (void)noResultButtonAction:(id)sender
{
    [self refreshTheProjectTableView];
}


@end
